package com.example.its2021606134chh.ThresholdModule;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.its2021606134chh.HttpUtil;
import com.example.its2021606134chh.R;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ThresholdShowFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ThresholdShowFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "param2";
    private String url = "http://121.9.253.237:8888/traffic/api/v2/get_all_sense";
    OkHttpClient okHttpClient = new OkHttpClient();

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private TargetShow targetShowTemperature;
    private TargetShow targetShowHumidity;
    private TargetShow targetShowLight;
    private TargetShow targetShowCo2;
    private TargetShow targetShowPM25;
    private TargetShow targetShowRoad;
    private Timer timer;
    private TimerTask timerTask;

    public ThresholdShowFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ThresholdShowFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ThresholdShowFragment newInstance(String param1, String param2) {
        ThresholdShowFragment fragment = new ThresholdShowFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_threshold_show, container, false);
        Handler handler = new Handler();
        // Inflate the layout for this fragment
        targetShowTemperature = (TargetShow) view.findViewById(R.id.targetShowTemperature);
        targetShowHumidity = (TargetShow) view.findViewById(R.id.targetShowHumidity);
        targetShowLight = (TargetShow) view.findViewById(R.id.targetShowLight);
        targetShowCo2 = (TargetShow) view.findViewById(R.id.targetShowCo2);
        targetShowPM25 = (TargetShow) view.findViewById(R.id.targetShowPM25);
        targetShowRoad = (TargetShow) view.findViewById(R.id.targetShowRoad);
        timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                new Thread(() -> {
                    HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                        @Override
                        public void onFailure(Exception e) {

                        }

                        @Override
                        public void onResponse(String json) {
                            Gson gson = new Gson();
//                        Log.i("TAG", "RUN1");
                            ThresholdParams params = gson.fromJson(json, ThresholdParams.class);
                            targetShowTemperature.setText2(1000, params.getTemperature());
                            targetShowTemperature.invalidate();
                            targetShowHumidity.setText2(30, params.getHumidity());
                            targetShowHumidity.invalidate();
                            targetShowPM25.setText2(1500, params.getPm25());
                            targetShowPM25.invalidate();
                            targetShowCo2.setText2(150, params.getCo2());
                            targetShowCo2.invalidate();
                            targetShowLight.setText2(20, params.getLightIntensity());
                            targetShowLight.invalidate();
                        }
                    }, "get_all_sense", new String[]{"UserName"}, "user1");

                    HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                        @Override
                        public void onFailure(Exception e) {

                        }

                        @Override
                        public void onResponse(String json) {
                            Gson gson = new Gson();
//                            Log.i("TAG", "RUN2");
                            ThresholdRoad RoadParams = gson.fromJson(json, ThresholdRoad.class);
                            targetShowRoad.setText2(1, String.valueOf(RoadParams.getStatus()));
                            targetShowRoad.invalidate();
                        }
                    }, "get_road_status", new String[]{"RoadId", "UserName"}, 1, "user1");
                }).start();
            }
        };
        timer.schedule(timerTask, 0, 3000);
        targetShowTemperature.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ThresholdActivity.class);
                startActivity(intent);
            }
        });
        targetShowHumidity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ThresholdActivity.class);
                startActivity(intent);
            }
        });
        targetShowLight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ThresholdActivity.class);
                startActivity(intent);
            }
        });
        targetShowCo2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ThresholdActivity.class);
                startActivity(intent);
            }
        });
        targetShowPM25.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ThresholdActivity.class);
                startActivity(intent);
            }
        });
        targetShowRoad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ThresholdActivity.class);
                startActivity(intent);
            }
        });
        return view;
    }

    @Override
    public void onResume() {
        timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                new Thread(() -> {
                    HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                        @Override
                        public void onFailure(Exception e) {

                        }

                        @Override
                        public void onResponse(String json) {
                            Gson gson = new Gson();
//                        Log.i("TAG", "RUN1");
                            ThresholdParams params = gson.fromJson(json, ThresholdParams.class);
                            targetShowTemperature.setText2(1000, params.getTemperature());
                            targetShowHumidity.setText2(30, params.getHumidity());
                            targetShowPM25.setText2(1500, params.getPm25());
                            targetShowCo2.setText2(150, params.getCo2());
                            targetShowLight.setText2(20, params.getLightIntensity());
                        }
                    }, "get_all_sense", new String[]{"UserName"}, "user1");

                    HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                        @Override
                        public void onFailure(Exception e) {

                        }

                        @Override
                        public void onResponse(String json) {
                            Gson gson = new Gson();
//                            Log.i("TAG", "RUN2");
                            ThresholdRoad RoadParams = gson.fromJson(json, ThresholdRoad.class);
                            targetShowRoad.setText2(1, String.valueOf(RoadParams.getStatus()));
                        }
                    }, "get_road_status", new String[]{"RoadId", "UserName"}, 1, "user1");
                }).start();
            }
        };
        timer.schedule(timerTask, 0, 3000);
        super.onResume();
    }

    @Override
    public void onPause() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask =  null;
        }
        super.onPause();
    }

    private void initView() {

    }
}